package com.mao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mao.common.Result;
import com.mao.entity.Employee;
import com.mao.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;

/**
 * 员工管理
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService es;

    /**
     * 后台登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        Employee data = es.login(request, employee);
        if (data==null){
            return Result.error("用户名不存在！");
        }
        //3.校验密码
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!data.getPassword().equals(password)){
            return Result.error("密码错误！");
        }
        //4.查看账号是否被禁用
        if (data.getStatus()==0){
            return Result.error("账号被禁用！");
        }
        return Result.success(data);
    }

    /**
     * 后台退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return Result.success("退出成功");
    }

    /**
     * 新增员工
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public Result<String> save(HttpServletRequest request,@RequestBody Employee employee){
        String isTF = es.save(request, employee);
        return Result.success(isTF);
    }

    /**
     * 分页查询员工
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page,int pageSize,String name){
        Page<Employee> pageInfo = es.page(page, pageSize, name);
        return Result.success(pageInfo);
    }


    /**
     * 修改员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public Result<String> update(HttpServletRequest request,@RequestBody Employee employee){
       es.updateEmployee(request, employee);
        return Result.success("员工信息修改成功");
    }


    /**
     * 查询单个员工
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable String id){
        //1.根据前端传来的id查询员工信息
        Employee byId = es.getById(id);
        if (byId==null){
            return Result.error("查询失败");
        }
        return Result.success(byId);
    }

}
